import time

from selenium import webdriver
from selenium.webdriver.common.by import By

from common.logger import floggger
from dao.BaseRepository import BaseRepository

print("a?")

browser = webdriver.Chrome()
browser.maximize_window()
db = BaseRepository(collectionname="fgame")

mainurl = 'https://www.fgame.top/'

from selenium.common.exceptions import NoSuchElementException


# 封装一个函数，用来判断属性值是否存在
def isElementPresent(by, value):
    """
    用来判断元素标签是否存在，
    """
    try:
        element = browser.find_element(by=by, value=value)
    # 原文是except NoSuchElementException, e:
    except NoSuchElementException as e:
        # 发生了NoSuchElementException异常，说明页面中未找到该元素，返回False
        return False
    else:
        # 没有发生异常，表示在页面中找到了该元素，返回True
        return True


def main():
    browser.get(mainurl)
    browser.find_element_by_xpath("/html/body/div[2]/div/div[1]/button").click()
    time.sleep(1)
    browser.find_element_by_xpath("/html/body/div/header/div/div/div[4]/div[1]").click()
    time.sleep(1)
    browser.find_element_by_xpath('//*[@id="login"]/div/form/div[1]/input').send_keys("terrydash")
    time.sleep(1)
    browser.find_element_by_xpath('//*[@id="login"]/div/form/div[2]/input').send_keys("52xuguoxu")
    time.sleep(1)
    browser.find_element_by_xpath('//*[@id="login"]/div/form/button').click()
    time.sleep(1)

    for page in range(1, 91):
        getpage(page)
        # try:
        #     getpage(page)
        # except Exception as e:
        #     continue
        #     floggger.error(str(e))


def getpage(num):
    gameurls = []
    url = 'https://www.fgame.top/page/{}'.format(num)
    browser.get(url)
    elements = browser.find_elements_by_class_name("col-lg-6")
    for ele in elements:
        for a in ele.find_elements_by_tag_name("a"):
            gurl = str(a.get_attribute("href"))
            if '/fgame/' in gurl and '/fgame/author/' not in gurl:
                gameurls.append(gurl)

    for gameurl in gameurls:
        print(gameurl)
        dataid = int(gameurl.lower().replace(r"https://www.fgame.top/fgame/", "").replace(r".html", ""))
        _, num, _ = db.search_no_page({'gameid': dataid})
        if num == 0:
            getdetail(gameurl, dataid)


def getdetail(url, dataid=None):
    browser.get(url)
    if dataid is not None:
        if isElementPresent(by=By.XPATH, value='//*[@id="cao_widget_pay-2"]/div[2]/div[2]/button'):
            browser.find_element_by_xpath('//*[@id="cao_widget_pay-2"]/div[2]/div[2]/button').click()
            time.sleep(1)
            if isElementPresent(by=By.XPATH, value='/html/body/div[2]/div/div[3]/button[2]'):
                browser.find_element_by_xpath('/html/body/div[2]/div/div[3]/button[2]').click()
                time.sleep(1)
            if isElementPresent(by=By.XPATH, value='/html/body/div[2]/div/div[3]/button[1]') and str(
                    browser.find_element_by_xpath('/html/body/div[2]/div/div[3]/button[1]').text).lower() == "ok":
                browser.find_element_by_xpath('/html/body/div[2]/div/div[3]/button[1]').click()
                time.sleep(1)

        game = {}
        game["gameid"] = dataid
        game['name'] = browser.find_element_by_xpath('//*[@id="post-' + str(dataid) + '"]/div[2]/div/header/h1').text
        game['introduce'] = browser.find_element_by_xpath('//*[@id="cao_widget_pay-2"]/div[3]/ul/li[2]/span[2]').text
        game['activecode'] = browser.find_element_by_xpath('//*[@id="bdt-modal-12dfc1f5"]/div/div[2]').text.strip()
        if isElementPresent(by=By.XPATH, value='//*[@id="cao_widget_pay-2"]/div[2]/div[2]/a[2]'):
            game['zp_url'] = browser.find_element_by_xpath(
                '//*[@id="cao_widget_pay-2"]/div[2]/div[2]/a[2]').get_attribute(
                "href")
        browser.get(url='https://www.fgame.top/go?post_id={}'.format(str(dataid)))

        # res = r.text.replace("<script type='text/javascript'>", "").replace("window.location=", "").replace("'",
        #                                                                                                     "").replace(
        #     ";setTimeout(function(){window.close()},2000)", "").replace("</script>").strip()
        time.sleep(3)
        if str(browser.current_url).startswith("https://pan.baidu.com"):
            game['download_url'] = browser.current_url
            floggger.debug(game)
            db.insert_one(game)
    else:
        floggger.debug(dataid + '已经下载过了')


if __name__ == "__main__":
    main()
